package scau.gsmg.misp.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.stereotype.Repository;

import scau.gsmg.misp.dao.BaseDAO;
import scau.gsmg.misp.dao.IMessageDAO;
import scau.gsmg.misp.vo.UserRole;

@Repository
public class MessageDAO extends BaseDAO implements IMessageDAO{

	@Override
	public String searcRoles(int id) {
		// TODO Auto-generated method stub
		boolean flag = false;
		Session session = getSession();
		List roles=new ArrayList();
		String r="";
		try {
			String hql = "from UserRole where id =?";
			Query query = session.createQuery(hql);
			query.setParameter(0, id);
			List<UserRole> list=query.list();
//			if(list.size())
			for(UserRole ur : list){
				//HashMap<String, Object> jsonMap = new HashMap<String, Object>();
				//jsonMap.put("role",ur.getRole().getName());
				//roles.add(jsonMap);
				r=ur.getRole().getName() + "  ";
			}
			flag = true;
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}
		return r;
//		return false;
	}

	@Override
	public boolean searchPasswd(int id ,String password) {
		// TODO Auto-generated method stub
		boolean flag = false;
		Session session = getSession();
		try {
			String hql = "from User where id =? and password =?";
			Query query = session.createQuery(hql);
			query.setParameter(0, id);
			query.setParameter(1, password);
			List list=query.list();
			if(list.size()!=0){
				flag = true;
			}
			
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}
		return flag;
	}

	@Override
	public boolean updatePasswd(int id,String password) {
		// TODO Auto-generated method stub
		boolean flag = false;
		Session session = getSession();
		Transaction tx = session.beginTransaction();
		try {
//			update Role r set r.name=?,r.roleCode=?,r.des?cription=? where r.id=?
			String hql = "update User u set u.password=? where u.id=? ";
			Query query = session.createQuery(hql);
			query.setParameter(0, password);
			query.setParameter(1,id );
			query.executeUpdate();
			tx.commit();
			flag=true;
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}
		return flag;
	}

}
